package com.sparrow.manage.access;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;

@Service
public class AccessPVServiceImpl implements AccessPVService {

    private static Logger logger = LoggerFactory.getLogger(AccessPVServiceImpl.class);

    @PersistenceUnit
    private EntityManagerFactory emf;

    /**
     * 访问量增加指定的值
     * @param accessNum
     */
    @Override
    public void incrementPVAccess(int accessNum){
        EntityManager em = null;
        EntityTransaction transaction = null;
        try{
            em = emf.createEntityManager();

            transaction = em.getTransaction();
            transaction.begin();

            long oldAccessNum = getAccessVolume(em);

            em.createNativeQuery("update tb_access_pv set access_ = " + (oldAccessNum + accessNum)).executeUpdate();

            transaction.commit();
        }catch (Exception e){
            if(transaction != null) transaction.rollback();
            logger.error(e.getMessage(), e);
        }finally {
            if(em != null){
                em.close();
            }
        }
    }

    @Override
    public long queryAccessNum() {
        EntityManager em = null;
        try{
            em = emf.createEntityManager();
            return getAccessVolume(em);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }finally {
            if(em != null){
                em.close();
            }
        }
        return 0;
    }

    private long getAccessVolume(EntityManager em){
        Object oldAccess = em.createNativeQuery("select access_ from tb_access_pv").getSingleResult();
        if(oldAccess == null){
            oldAccess = Long.valueOf(0);
        }
        return (Integer) oldAccess;
    }
}
